package com.hdx.server.service.impl;


import com.hdx.model.dto.GoodsSalesDTO;
import com.hdx.model.entity.Orders;
import com.hdx.model.vo.*;
import com.hdx.server.mapper.OrderMapper;
import com.hdx.server.mapper.UserMapper;
import com.hdx.server.service.ReportService;
import com.hdx.server.service.WorkspaceService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    //营业额统计
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        //1
        //新建dateLit集合,将第一天日期放入dateList集合
        //while遍历(!begin.equals(end)) 获取begin的后一天,将begin的后一天放入dateList集合,直到begin=end
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //2
        //新建turnoverList集合
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        //遍历dateList集合,将date日期类型转为LocalDateTime类型 获得日期最早时间和日期最晚时间

        List<Double> turnoverList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //新建map放入日期最早时间和日期最晚时间和已完成状态对数据库进行查询

            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            //turnover = turnover == null ? 0.0 : turnover; 将turnover加入turnoverList集合
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //3
        //封装返回TurnoverReportVO 里面两个值需要用,分隔
        turnoverReportVO.setTurnoverList(StringUtils.join(turnoverList, ","));
        turnoverReportVO.setDateList(StringUtils.join(dateList, ","));
        return turnoverReportVO;
    }

    //查询用户数据
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        //1
        //新建dateLit集合,将第一天日期放入dateList集合
        //while遍历(!begin.equals(end)) 获取begin的后一天,将begin的后一天放入dateList集合,直到begin=end
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //2
        //新建newUserList集合和新建totalUserList集合
        ArrayList<Integer> newUserList = new ArrayList<>();
        ArrayList<Integer> totalUserList = new ArrayList<>();
        //遍历dateList集合,将date日期类型转为LocalDateTime类型 获得日期最早时间和日期最晚时间
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //新建map放入日期最晚时间对数据库进行查询总用户数totalUser,在放入最新日期对数据库进行查询新增用户数量newUser
            Map map = new HashMap();
            map.put("end", beginTime);
            Integer totalUser = userMapper.countByMap(map);
            map.put("begin", endTime);
            //将totalUser放入totalUserList,将newUser放入newUserList
            Integer newUser = userMapper.countByMap(map);
            //将totalUser放入totalUserList,将newUser放入newUserList
            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }
        //3
        //封装返回UserReportVO 里面三个值需要用,分隔
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setNewUserList(StringUtils.join(newUserList, ","));
        userReportVO.setTotalUserList(StringUtils.join(totalUserList, ","));
        userReportVO.setDateList(StringUtils.join(dateList, ","));

        return userReportVO;
    }

    //订单统计
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {

        //1
        //新建dateLit集合,将第一天日期放入dateList集合
        //while遍历(!begin.equals(end)) 获取begin的后一天,将begin的后一天放入dateList集合,直到begin=end
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //2
        //新建orderCountList集合和新建validOrderCountList集合
        ArrayList<Integer> orderCountList = new ArrayList<>();
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        //遍历dateList集合,将date日期类型转为LocalDateTime类型 获得日期最早时间和日期最晚时间
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //私有方法getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status)获取orderCount(status=null)和validOrderCount(status=5)
            //私有方法是新建map放入begin,end,status对数据库进行查询
            Integer orderCount = getOrderCount(beginTime, endTime,null);
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            //将orderCount放入orderCountList,将validOrderCount放入validOrderCountList
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        //3
        //将totalOrderCount用stream.reduce转为integer类型 将和validOrderCountList用stream.reduce转为integer类型
        //计算时间区间内的订单总数量
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        //计算时间区间内的有效订单数量
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount获取订单完成率
        Double orderCompletionRate=0.0;
        orderCompletionRate = validOrderCount.doubleValue()/totalOrderCount;
        //4
        // 封装返回OrderReportVO 里面三个值需要用,分隔,另外三个值直接设置
        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(StringUtils.join(dateList,","));
        orderReportVO.setValidOrderCountList(StringUtils.join(validOrderCountList,","));
        orderReportVO.setOrderCountList(StringUtils.join(orderCountList,","));
        orderReportVO.setValidOrderCount(validOrderCount);
        orderReportVO.setTotalOrderCount(totalOrderCount);
        orderReportVO.setOrderCompletionRate(orderCompletionRate);


        return orderReportVO;
    }

    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);

        return orderMapper.countByMap(map);
    }

    //销量排名top10
    @Override
    public SalesTop10ReportVO getSalesTop10ReportVO(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //根据locaDateTime查询数据库订单前10的集合
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        //将订单前10集合用strsam.map获取订单的名字集合,用,分隔
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        //将订单前10集合用stream.map获取订单的数量集合,用,分隔
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");
        //封装返回SaleTop10ReportVO
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(nameList);
        salesTop10ReportVO.setNumberList(numberList);
        return salesTop10ReportVO;
    }

    /**
     * 导出运营数据报表
     *
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}